package com.firewolf.rabbitmq;

import java.io.IOException;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

import utils.ConnectionUtils;

public class Worker1 {
	private static final String QUEUE_NAME = "work_queue2";

	public static void main(String[] args) throws Exception {

		Connection conn = ConnectionUtils.getMQConnection();

		final Channel channel = conn.createChannel();

		channel.queueDeclare(QUEUE_NAME, false, false, false, null);
		
		channel.basicQos(1);
		
		Consumer consumer = new DefaultConsumer(channel) { // 创建消费者
			@Override
			public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
					byte[] body) throws IOException {
				try {
					String message = new String(body, "UTF-8");
					System.out.println("接收到消息：" + message);
					Thread.sleep(1000);//模拟处理消息耗时
				} catch (InterruptedException e) {
					e.printStackTrace();
				}finally {
					//手动告知RabbitMQ已经处理消息
					channel.basicAck(envelope.getDeliveryTag(), false);
				}
			}
		};
		boolean autoAck = false;//关闭自动回复，使用手动回复
		channel.basicConsume(QUEUE_NAME, autoAck, consumer);
	}
}
